<template>
  <div class="ff-regular">
    <Modal v-model="showPop" width="40" :closable="false" :mask-closable="false" class-name="vertical-center-modal">
      <div slot="header" class="head-sty">
        <div class="title ff-bold">{{ form.id ? $t('user.editShippingAddress') : $t('user.addedShippingAddress') }}
        </div>
        <Icon type="md-close" class="close" @click="closeMet()" />
      </div>
      <div class="content-sty">
        <!-- 姓名 -->
        <div class="list-sty">
          <div class="item-list">
            <div class="label-name"><span>*</span> {{ $t('user.name') }}</div>
            <Input v-model="form.name" :placeholder="$t('personal.FirstName')" class="input-sty" />
          </div>
          <div class="item-list">
            <div></div>
            <Input v-model="form.surname" :placeholder="$t('personal.LastName')" class="input-sty" />
          </div>
        </div>
        <!-- 所在地址 -->
        <div class="list-sty">
          <div class="item-list">
            <div class="label-name"><span>*</span> {{ $t('user.locationAddress') }}</div>
            <!-- 国家 -->
            <Select v-model="form.countryCode" @on-change="onCountryChange" @on-clear="clearMet"
              :placeholder="$t('user.country')" filterable class="select-sty" clearable>
              <div class="img-select" slot="prefix">
                <Avatar v-if="currentCountryImage" :src="currentCountryImage" size="small" />
              </div>
              <Option v-for="item in countryList" :value="item.code" :label="item.text" :key="item.code">
                <div class="option-content">
                  <img v-if="item.flagImg" class="logo" :src="item.flagImg" alt="" />
                  <span>{{ item.text }}</span>
                </div>
              </Option>
            </Select>
          </div>
          <div class="item-list">
            <div></div>
            <!-- 省份 -->
            <Select v-model="form.provinceCode" :disabled="!form.countryCode || provinceList.length == 0"
              :label-in-value="true" :placeholder="$t('user.province')" @on-change="onSelectProvince"
              @on-clear="clearProMet" filterable class="select-sty" clearable>
              <Option v-for="item in provinceList" :value="item.pid" :key="item.pid">
                {{ item.nameLocal }}
              </Option>
            </Select>
          </div>
          <div class="item-list">
            <div></div>
            <!-- 市区 -->
            <Select v-if="cityList && cityList.length != 0" v-model="form.cityCode" ref="vehicleType"
              :disabled="!form.provinceCode || cityList.length == 0" :label-in-value="true"
              :placeholder="$t('user.city')" @on-change="onSelectCity" filterable class="select-sty" clearable>
              <Option v-for="item in cityList" :value="item.id" :key="item.id">
                {{ item.nameLocal }}
              </Option>
            </Select>
            <Input v-if="!cityList || cityList.length == 0" v-model="form.cityText" :disabled="!form.provinceCode"
              class="city-input" :placeholder="$t('user.city')" />
          </div>
        </div>
        <!-- 详细地址 -->
        <div class="list-sty">
          <div class="item-list">
            <div class="label-name"><span>*</span> {{ $t('user.detailedAddress') }}</div>
            <Input v-model="form.addressDetail" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" class="text-area"
              :placeholder="$t('user.info_input_default')" />
          </div>
        </div>
        <!-- 门牌号 -->
        <div class="list-sty">
          <div class="item-list">
            <div class="label-name">{{ $t('user.door_number') }}</div>
            <Input v-model="form.doorNumber" :placeholder="$t('user.please_write_door')" class="input-sty" />
          </div>
        </div>
        <!-- 收件公司 -->
        <div class="list-sty">
          <div class="item-list">
            <div class="label-name">{{ $t('user.receive_email') }}</div>
            <Input v-model="form.consigneeCompany" :placeholder="$t('user.tip_input_content')" class="input-sty" />
          </div>
        </div>
        <!-- 邮编 -->
        <div class="list-sty">
          <div class="item-list">
            <div class="label-name"><span>*</span> {{ $t('user.postcode') }}</div>
            <Input v-model="form.postalCode" placeholder="" class="input-sty " />
          </div>
        </div>
        <!-- 邮编-提示 -->
        <div class="list-sty">
          <div class="pos-sty" style="flex: 1;">
            <div class="tip-text" v-if="tip1">{{ $t('user.code_tip_text', { code: defaultCode }) }}</div>
          </div>
        </div>
        <!-- 手机号 -->
        <div class="end-sty">
          <div class="item-list">
            <div class="label-name"><span>*</span> {{ $t('user.mobile') }}</div>
            <div></div>
          </div>
          <div class="item-list">
            <!--国际区号-->
            <Select v-model="form.regionCodeCountry" :label-in-value="true" :placeholder="$t('user.pleaseSelect')"
              filterable clearable class="select-sty" @on-change="regionChange" @on-clear="clearCodeMet"
              style="width: 184px;">
              <Option v-for="(item, index) in regionCodeList" :label="item.text" :value="item.code + item.regionCountry"
                :key="item.code + index">
                <div class="region-code">
                  <img class="region-code-icon" :src="item.flagImg" alt="" />
                  <span>{{ item.text }}</span>
                </div>
              </Option>
            </Select>
            <Input v-model="form.mobile" @on-change="validateInput" maxlength="20" class="input-sty" style="flex: 1;" />
          </div>
        </div>
        <!-- 重复填写手机区号提示 -->
        <div class="list-sty" v-if="tip2">
          <div style="width: 184px;"></div>
          <div class="pos-sty" style="flex: 1;">
            <div class="tip-text">{{ $t('user.repeat_code', { code: regionCode }) }}</div>
          </div>
        </div>
        <!-- 默认地址 -->
        <div class="list-sty">
          <div class="label-default-text">{{ $t('user.defaultAddress') }}</div>
          <i-switch true-color="#FF186B" false-color="#D9D9D9" v-model="form.isDefault" class="switch-sty"
            style="border: none !important;"></i-switch>
        </div>
      </div>
      <div slot="footer" class="footer-wrap">
        <div class="cancel-text" @click="closeMet()">{{ $t('pay.cancel') }}</div>
        <div class="confirm-text" v-if="!form.id" @click="createAddress">{{ $t('personal.Search-confirm') }}</div>
        <div class="confirm-text" v-else @click="editAddress">{{ $t('personal.Search-confirm') }}</div>
      </div>
    </Modal>
    <!-- 门牌号中已包含‘所在地址’信息，请检查是否有重复输入，并进行相应修改。 -->
    <rules-pop-one ref="oneRef" @confirmEmit="confirmEmit" @closeEmit="closeEmit"></rules-pop-one>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { addressExamineRepetition } from "@/common/common";
import { addressAdd, addressEdit } from "@/api/address";
import { countryAddressList, cityApiList } from "@/api/administrativedivisions";
import { pointUser } from "@/common/point/api-hook";//打点日志
import rulesPopOne from './rules-pop-one.vue';
export default {
  components: { rulesPopOne },
  data() {
    return {
      showPop: false,
      form: {
        isDefault: false
      },
      tip1: false,
      tip2: false,
      currentCountryImage: "", // 当前国家图片
      cityList: [], // 市区列表
      provinceList: [], //省份市区
      regionCode: '',
      defaultCode: ''
    }
  },
  computed: {
    ...mapState({
      userCurrency: state => state.user.userCurrency,
      userInfo: state => state.user.userInfo,
      // 国家列表
      countryList: (state) => {
        let list = [];
        if (state.config.config) {
          list = state.config.config.countryList;
        }
        return list;
      },
      // 国际区号
      regionCodeList: (state) => {
        let list = [];
        if (state.config.config) {
          list = state.config.config.regionCodeList;
        }
        return list;
      },
    })
  },
  watch: {
    form: {
      handler(newValue) {
        if (Object.keys(newValue).length > 0) {
          this.checkRegionCode();
        }
      },
      deep: true
    }
  },
  methods: {
    open(info) {
      if (info) {
        this.form = info;
        if (info.addressId) {
          this.form.id = info.addressId;
          this.form.isDefault = false;
        } else {
          this.form.id = info.id;
          this.form.isDefault = info.isDefault;
        }
        // 如果有this.form.id说明是编辑
        if (this.form.id) {
          this.type = 2;
        }
        this.form.name = info.recipientName.split(",")[0];
        this.form.surname = info.recipientName.split(",")[1];
        this.form.regionCodeCountry = info.regionCode + info.regionCountry;
        this.regionCode = info.regionCode;
        this.onCountryAddressList(info.countryCode, "provinceList");
        if (info.provinceCode) this.getCityList(info.provinceCode, "cityList");
      }

      const contentElement = document.querySelector('.content-sty');
      contentElement.scrollTop = 0;

      this.showPop = true;
    },
    closeMet() {
      this.showPop = false;
      this.clearInfo();
    },
    // 清空数据
    clearInfo() {
      this.currentCountryImage = "";
      this.form = {
        id: "",
        surname: "", // 姓
        name: "", // 名
        addressDetail: "", // 街道地址，详细地址
        areaCode: "", // 区code
        areaText: "", // 区文本
        cityCode: "", // 市code
        cityText: "", // 市文本
        countryCode: "", // 国家编码
        countryText: "",
        districtCode: "", // 地址编码
        regionCode: "", // 手机国际区号
        isDefault: false, // 是否默认地址
        mobile: "", // 手机号
        phone: "", // 电话
        postalCode: "", // 邮政编码
        provinceCode: "",
        provinceText: "", // 省份文本
        recipientName: "", // 收件人姓名
        townText: "", // 文本
        regionCountry: "",
        regionCodeCountry: "", // 区号+国家
        doorNumber: '',
        consigneeCompany: ''
      };
      this.tip1 = false;
    },
    // 选择国家
    onCountryChange(value) {
      let info = this.countryList.find((item) => {
        return item.code == value;
      });
      if (!info) return;//如果没数据不继续执行
      this.form.countryText = info.text;
      this.currentCountryImage = info.flagImg;
      this.form.provinceCode = "";
      this.form.cityCode = "";
      this.form.areaCode = "";
      this.form.provinceText = "";
      this.form.cityText = "";
      this.form.areaText = "";
      this.onCountryAddressList(info.code, "provinceList");// 获取省列表
    },
    // 获取省列表
    onCountryAddressList(code, type) {
      this[type] = [];
      countryAddressList(code).then((res) => {
        this[type] = res.result;
      });
    },
    // 选择省份
    onSelectProvince(info) {
      if (!info) return;//如果没数据不继续执行
      this.getCityList(info.value, "cityList");// 获取市列表
      this.form.provinceText = info.label;
      this.form.cityCode = "";
      this.form.areaCode = "";
      this.form.cityText = "";
      this.form.areaText = "";
    },
    // 获取市列表
    getCityList(code, type) {
      this[type] = [];
      cityApiList(code).then((res) => {
        this[type] = res.result;
      });
    },
    // 选择城市
    onSelectCity(info) {
      if (!info) return;//如果没数据不继续执行
      this.cityList.forEach((item) => {
        if (item.id == info.value) {
          this.form.postalCode = item.postalCode;
        }
      })
      this.form.cityText = info.label;
      this.form.areaCode = "";
      this.form.areaText = "";
    },
    // 国家清除选中
    clearMet() {
      this.currentCountryImage = '';
      this.form.provinceCode = '';
      this.form.cityCode = '';
      this.form.cityText = '';
      this.provinceList = [];
      this.cityList = [];
    },
    // 省份清除选中
    clearProMet() {
      this.form.cityCode = '';
      this.form.cityText = '';
      this.cityList = [];
    },
    clearCodeMet() {
      this.checkRegionCode();
    },
    // 区号赋值
    regionChange(item) {
      if (!item) return;
      let selectedOption = this.regionCodeList.find((option) => option.code + option.regionCountry === item.value);
      this.form.regionCode = selectedOption.code || "";
      this.form.regionCountry = selectedOption.regionCountry || "";
      this.regionCode = selectedOption.code;
      this.checkRegionCode();
    },
    // 手机号校验
    validateInput() {
      const regex = /^[0-9+]*$/;
      if (!regex.test(this.form.mobile)) {
        this.$Message.warning(this.$t('user.input_rules_tip'));
      }
      this.checkRegionCode();
    },
    checkRegionCode() {
      const mobile = this.form.mobile;
      const regionCode = this.regionCode;
      if (regionCode && mobile && mobile.length >= regionCode.length && mobile.slice(0, regionCode.length) === regionCode && regionCode) {
        this.tip2 = true;
      } else {
        this.tip2 = false;
      }
    },
    // 新增、编辑的公共验证
    validateForm() {
      if (!this.form.name) {
        this.$Message.error(this.$t('user.pleaseEnter') + this.$t('personal.FirstName'));
        return false;
      }
      if (!this.form.surname) {
        this.$Message.error(this.$t('user.pleaseEnter') + this.$t('personal.LastName'));
        return false;
      }
      if (!this.form.countryCode) {
        this.$Message.error(this.$t('user.pleaseSelect') + this.$t('user.country'));
        return false;
      }
      if (!this.form.provinceCode) {
        this.$Message.error(this.$t('user.pleaseSelect') + this.$t('user.province'));
        return false;
      }
      if ((!this.form.cityCode && !this.form.cityText) || !this.form.cityText || this.form.cityText == '') {
        this.$Message.error(this.$t('user.pleaseSelect') + this.$t('user.city'));
        return false;
      }
      if (!this.form.addressDetail) {
        this.$Message.error(this.$t('user.pleaseEnter') + this.$t('user.detailedAddress'));
        return false;
      }
      if (!this.form.postalCode) {
        this.$Message.error(this.$t('user.pleaseEnter') + this.$t('user.postcode'));
        return false;
      }
      if (!this.form.regionCodeCountry) {
        this.$Message.error(this.$t('user.pleaseSelect') + this.$t('user.mobileAreaCode'));
        return false;
      }
      if (!this.form.mobile) {
        this.$Message.error(this.$t('user.pleaseEnter') + this.$t('personal.PhoneNumber'));
        return false;
      }
      return true;
    },
    // 添加地址
    createAddress() {
      // 地址必填校验
      if (!this.validateForm()) { return }
      // 姓名拼接传值
      this.form.recipientName = `${this.form.name},${this.form.surname}`;

      addressExamineRepetition(this.form, true).then(() => {
        console.log("新增地址成功");
        this.addPort();//新建地址接口
      }).catch((err) => {
        console.log("新增地址失败", err);
        this.showPop = false;
        let str = '';
        if (err.val) {
          str = this.$t(err.text, { val: err.val });
        } else {
          str = this.$t(err.text);
        }
        this.$refs.oneRef.open(str, this.$t('user.back_edit_text'), '', 1, 1);
      })
    },
    addPort() {
      addressAdd(this.form).then(() => {
        pointUser('actions', '2008');
        this.$Message.success(this.$t("user.addSuccessfully"));
        this.closeMet();
        this.$emit('updateMet');
      });
    },
    // 编辑地址
    editAddress() {
      // 地址必填校验
      if (!this.validateForm()) { return }
      // 姓名拼接传值
      this.form.recipientName = `${this.form.name},${this.form.surname}`;

      addressExamineRepetition(this.form, true).then(() => {
        console.log("编辑地址成功");
        this.editPort();//编辑地址接口
      }).catch((err) => {
        console.log("编辑地址失败");
        this.showPop = false;
        let str = '';
        if (err.val) {
          str = this.$t(err.text, { val: err.val });
        } else {
          str = this.$t(err.text);
        }
        this.$refs.oneRef.open(str, this.$t('user.back_edit_text'), '', '', 2);
      })
    },
    editPort() {
      addressEdit(this.form).then(() => {
        this.$Message.success(this.$t("user.changeSuccessfully"));
        this.closeMet();
        this.$emit('updateMet');
      });
    },
    confirmEmit(val1, val2) {
      if (val1 == 1) {
        if (val2 == 1) {
          this.addPort();
        } else {
          this.editPort();
        }
      }
    },
    closeEmit() {
      this.showPop = true;
    }
  }
}
</script>

<style lang="less" scoped>
:deep(.ivu-modal-content) {
  border-radius: 12px;

  .ivu-modal-header {
    border: none;
    padding: 32px 32px 0 32px;
  }

  .ivu-modal-body {
    padding: 0 32px 0 32px;
  }

  .ivu-modal-footer {
    border: none;
    padding: 16px 32px 24px 32px;
  }
}

.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;

  .head-sty {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-weight: 500;
      font-size: 20px;
      color: #1E1714;
      line-height: 28px;
    }

    .close {
      color: #1E1714;
      font-size: 36px;
      font-weight: 500;
      cursor: pointer;
    }
  }

  .content-sty {
    height: 50vh;
    overflow-y: auto;

    .list-sty {
      display: flex;
      align-items: end;
      gap: 16px;

      .item-list {
        flex: 1;

        .label-name {
          font-weight: 400;
          font-size: 14px;
          color: #1E1714;
          line-height: 23px;
          margin-top: 24px;
          margin-bottom: 12px;

          span {
            color: #FF186B;
          }
        }

        .input-sty {
          :deep(.ivu-input) {
            min-height: 48px;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 14px;
            line-height: 24px;
          }
        }

        .text-area {
          :deep(.ivu-input) {
            min-height: 48px;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 14px;
            line-height: 24px;
          }
        }

        .city-input {
          :deep(.ivu-input) {
            min-height: 48px;
            padding-left: 16px;
          }
        }

        .select-sty {

          .img-select {
            display: flex;
            align-items: center;
          }

          :deep(.ivu-select-selection) {
            min-height: 48px;
            padding-left: 16px;

            .ivu-select-input {
              display: inline-block;
              min-height: 48px;
              font-size: 14px;
              line-height: 24px;
            }

            .ivu-select-placeholder {
              min-height: 48px;
              padding: 12px 16px;
              font-size: 14px;
              line-height: 24px;
            }

            .ivu-select-arrow {
              font-size: 20px;
            }
          }

          .option-content {
            display: flex;
            align-items: center;

            .logo {
              display: inline-block;
              width: 30px;
              margin-right: 4px;
            }
          }
        }
      }

      .pos-sty {
        width: 50%;

        .tip-text {
          font-weight: 400;
          font-size: 16px;
          color: #FF186B;
          line-height: 19px;
          margin-top: 8px;
        }
      }

    }

    .end-sty {
      .item-list {
        display: flex;
        align-items: end;
        gap: 16px;

        .label-name {
          font-weight: 400;
          font-size: 14px;
          color: #1E1714;
          line-height: 23px;
          margin-top: 24px;
          margin-bottom: 12px;

          span {
            color: #FF186B;
          }
        }

        .input-sty {
          :deep(.ivu-input) {
            min-height: 48px;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 14px;
            line-height: 24px;
          }
        }

        .select-sty {
          :deep(.ivu-select-selection) {
            min-height: 48px;

            .ivu-select-input {
              min-height: 48px;
              padding: 12px 16px;
              font-size: 14px;
              line-height: 24px;
            }

            .ivu-select-placeholder {
              min-height: 48px;
              padding: 12px 16px;
              font-size: 14px;
              line-height: 24px;
            }

            .ivu-select-arrow {
              font-size: 20px;
            }
          }
        }
      }
    }


    .list-sty {
      display: flex;
      align-items: end;
      gap: 16px;

      .label-default-text {
        font-weight: 400;
        font-size: 14px;
        color: #1E1714;
        line-height: 23px;
        margin-top: 24px;
      }

      .switch-sty {
        margin-top: 24px;
      }

      :deep(.ivu-switch:focus) {
        box-shadow: none !important;
        border: none !important;
      }
    }
  }

  // .content-sty::-webkit-scrollbar {
  //   display: none;
  // }

  .footer-wrap {
    display: flex;
    justify-content: end;
    gap: 24px;

    .cancel-text {
      height: 46px;
      padding: 12px 40px;
      border-radius: 8px 8px 8px 8px;
      border: 1px solid #E5E5E5;
      font-weight: 500;
      font-size: 16px;
      color: #1E1714;
      line-height: 19px;
      cursor: pointer;
    }

    .confirm-text {
      height: 46px;
      padding: 12px 40px;
      background: #F21473;
      border-radius: 8px 8px 8px 8px;
      font-weight: 500;
      font-size: 16px;
      color: #FFFFFF;
      line-height: 19px;
      cursor: pointer;
    }
  }
}

.region-code {
  display: flex;
  align-items: center;

  .region-code-icon {
    width: 30px;
    // border-radius: 50%;
    overflow: hidden;
    margin-right: 2px;
  }
}
</style>
